package cn.getway.filter;

import cn.getway.config.web.RequestPathConfig;
import cn.getway.config.web.ResponseStatusCode;
import cn.getway.config.web.ResponseMessage;
import cn.getway.utils.GsonTool;
import com.netflix.util.Pair;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
import static com.netflix.zuul.context.RequestContext.getCurrentContext;

/**
 * 该过滤器专注于用户身份的认证及token的分发
 *
 * @Author: 毛苏宇
 * User: me
 * Date: 2020/6/21
 * Time: 19:22
 * Description:
 */
@Component
public class LoginFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //不需要进行校验的地址，如登录地址
        final String requestURI = getCurrentContext().getRequest().getRequestURI();
        for (String loginUrl : RequestPathConfig.getIgnoreUrls()) {
            if (requestURI.contains(loginUrl)) {
                System.out.println("请求地址：" + requestURI);
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() {
        //获取该请求的上下文
        RequestContext context = getCurrentContext();
        context.getResponse().setContentType("text/html;charset=UTF-8");
        //得到微服务的响应
        InputStream stream = context.getResponseDataStream();
        HttpServletResponse response = context.getResponse();
        try {
            //响应体，微服务响应的内容
            String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
            final List<Pair<String, String>> originResponseHeaders = context.getOriginResponseHeaders();
            String jwtToken = "";
            for (Pair<String, String> originResponseHeader : originResponseHeaders) {
                if ("jwtToken".equals(originResponseHeader.first())) {
                    jwtToken = originResponseHeader.second();
                }
            }
            Cookie cookie = new Cookie("auth", URLEncoder.encode(jwtToken, "utf-8"));
            cookie.setPath("/gc");
            response.addCookie(cookie);
            context.setResponseBody(body);
            return null;
        } catch (IOException io) {
            System.out.println(io.getMessage());
            context.setResponseBody(GsonTool.objectToJson(new ResponseMessage(ResponseStatusCode.CODE_SYSTEM_ERROR, "系统IO错误",null)));
            return null;
        }
    }


}
